package batch

import (
	"fmt"
	"strings"

	"mariadb-operator/pkg/apis/finupgroup/v1alpha1"
	"mariadb-operator/pkg/constants"

	corev1 "k8s.io/api/core/v1"
)

func help(spec v1alpha1.BackupSpec) (string, string) {
	image := ""
	backupCMD := ""
	databases := strings.Join(strings.Split(spec.Executor.Databases, ","), " ")
	if spec.Executor.CMD == constants.BackupCMDXtrabackup {
		image = constants.DefaultXtrabackupImage
		// TODO
		// backupCMD = fmt.Sprintf()
	} else {
		image = constants.DefaultMysqldumpImage
		if databases == constants.BackupAllDatabases {
			backupCMD = fmt.Sprintf("mysqldump -h %v-0.%v -uroot -proot -A | gzip > %v", spec.Cluster, spec.Cluster, constants.BackupFileName)
		} else {
			backupCMD = fmt.Sprintf("mysqldump -h %v-0.%v -uroot -proot --databases %v | gzip > %v", spec.Cluster, spec.Cluster, databases, constants.BackupFileName)
		}
	}
	return image, backupCMD
}

func envs(spec v1alpha1.BackupSpec, name, namespace string) []corev1.EnvVar {
	if spec.StorageProvider.S3 != nil {
		forcePathStyle := ""
		if spec.StorageProvider.S3.ForcePathStyle {
			forcePathStyle = "true"
		}
		return []corev1.EnvVar{
			corev1.EnvVar{Name: "S3_REGION", Value: spec.StorageProvider.S3.Region},
			corev1.EnvVar{Name: "S3_ENDPOINT", Value: spec.StorageProvider.S3.Endpoint},
			corev1.EnvVar{Name: "S3_BUCKET", Value: spec.StorageProvider.S3.Bucket},
			corev1.EnvVar{Name: "S3_FORCEPATHSTYLE", Value: forcePathStyle},
			corev1.EnvVar{Name: "S3_CREDENTIALSSECRET", Value: spec.StorageProvider.S3.CredentialsSecret.Name},
			corev1.EnvVar{Name: "SECRETE_NAMESPACE", Value: namespace},
			corev1.EnvVar{Name: "CLUSTER_NAME", Value: name},
		}
	}
	if spec.StorageProvider.Qiniu != nil {
		return []corev1.EnvVar{
			corev1.EnvVar{Name: "QINIU_ACCESS_KEY", Value: spec.StorageProvider.Qiniu.AccessKey},
			corev1.EnvVar{Name: "QINIU_SECRET_KEY", Value: spec.StorageProvider.Qiniu.SecretKey},
			corev1.EnvVar{Name: "QINIU_TEST_BUCKET", Value: spec.StorageProvider.Qiniu.Bucket},
			corev1.EnvVar{Name: "QINIU_IO", Value: spec.StorageProvider.Qiniu.IO},
			corev1.EnvVar{Name: "QINIU_UP", Value: spec.StorageProvider.Qiniu.UP},
			corev1.EnvVar{Name: "QINIU_API", Value: spec.StorageProvider.Qiniu.API},
			corev1.EnvVar{Name: "SECRETE_NAMESPACE", Value: namespace},
			corev1.EnvVar{Name: "CLUSTER_NAME", Value: name},
		}
	}
	return nil
}
